/**
* 创建者：luyiming
* 该页面用于：
* 创建时间： 2020-03-06 21:47:29
*/
import Table from "@/components/Table";
import Pagination from "@/components/Pagination"; // 分页
import { getEnterpriseDeclarePermitLst, getLicenceBaseInfo, getDeclarePermitInfo,InsertDeclarePermit,getEnterpriseStatus,getEnterpriseType } from "@/api/RCIM/RCIM-licence";
import { getToken } from '@/utils/auth'
import { cloneDeep } from "lodash";
import moment from "moment";
export default {
    name: 'RcimLicenceDeclaration_view',
    components: {
        Table,
        Pagination
    },
    props: {
    },
    // 数据
    data() {
        return {
            timmer: [
				moment().subtract(1, 'months').format('YYYY-MM-DD'),
				moment().format('YYYY-MM-DD')
			],
            tableData: [
			],
			tableHead: [
				{
					prop: "reportingTime",
					label: "申报时间",
					width: "",
					align: "center"
				},
				{
					prop: "registrant",
					label: "登记人",
					width: "",
					align: "center"
				},
				{
					prop: "leadingCadre",
					label: "企业负责人",
					width: "",
					align: "center"
				},
				{
					prop: "operate",
					label: "操作",
					width: "",
					align: "center"
				}
			],
			listLoading: false,
			total: 0,
			listQuery: {
				page: 1,
				limit: 10,
                id: "",
                startTime: "",
                endTime: "",
                token: getToken()
            },
            showTimeLinePiker: {
                type: Boolean,
                default: () => true
            },
            unInitTimmer: {
                type: Boolean,
                default: () => false
            },
            datePickType: {
				format: "yyyy-MM-dd",
				precise: "daterange", // 精度 year/month/date/dates/ week/datetime/datetimerange/ daterange/monthrange
				longer: "30"
            },
            dialogVisible: false,
            licenceInfo: {
                licenceImgUrls: []
            },
            enterpriseTypeOptions: [{
                value: 1,
                label: '核技术利用1'
              }, {
                value: 2,
                label: '核技术利用2'
              }],
            enterpriseStatusOptions: [{
                value: 1,
                label: '正常'
              }, {
                value: 2,
                label: '注销'
            }],
            licenceImgUrls: [],
            isScan: false, // 是否是查看
			fileUpload: null,
			isGO: true,
        }
    },
    computed: {
        type() {
			const resultTime = Object.assign(
				{},
				{
					format: "yyyy-MM-dd",
					precise: "daterange",
					longer: "30"
				},
				this.datePickType
			);
			const { format, precise, longer } = resultTime;
			if (typeof format !== "string") {
				throw new Error("日期格式化不合法");
			}
			if (typeof precise !== "string") {
				throw new Error("日期选择器类型必须是string");
			}
			return resultTime;
		}
    },
    // 监听
    watch: {

    },
    // Vue实例初始化完成
    created() {

    },
    // Vue挂载完成
    mounted() {
		this.changeDate()
        this.getList()
        this.getEnterpriseOptions()
        this.getEnterpriseStatusOptions()
    },
    // Vue实例销毁前
    beforeDestroy(){

    },
    // 挂载的方法
    methods: {
        /**
         * @desc 获取单位类型选择框
         */
        async getEnterpriseOptions() {
            const {data} = await getEnterpriseType()
            console.log(data)
            this.enterpriseTypeOptions = data
        },
        /**
         * @desc 获取单位状态选择框
         */
        async getEnterpriseStatusOptions() {
            const {data} = await getEnterpriseStatus()
            this.enterpriseStatusOptions = data
        },
        /**
         * @desc 获取表格数据
         */
        async getList() {
			this.listLoading = true;
			const { data } = await getEnterpriseDeclarePermitLst(this.listQuery);
			this.total = data.total;
			this.tableData = data.data;
			this.listLoading = false;
        },
        /**
         * @desc 修改时间回调
         */
        changeDate() {
            const dateObj = {};
			if (/range/.test(this.type.precise)) {
				dateObj.startTime = moment(this.timmer[0]).format('YYYY-MM-DD')
				dateObj.endTime = moment(this.timmer[1]).format('YYYY-MM-DD') + ' 23:59:59'
			} else {
                // dateObj.time = this.timmer || "";
                dateObj.startTime = ""
                dateObj.endTime = ""
			}
            console.log(dateObj);
            this.listQuery = Object.assign({},this.listQuery,dateObj)
        },
        /**
         * @desc 搜索表格数据
         */
        searchLicenceList() {
            this.getList()
        },
        /**
         * @desc 申报点击
         */
        async handleChangeVisible() {
			this.isGO = true;
            this.isScan = false
            const { data } = await getLicenceBaseInfo();
            this.licenceInfo = data.entData
            this.dialogVisible = true
        },
        /**
         * @desc 表格数据详情
         */
        async handleEdit(row) {
			this.isGO = false
            this.isScan = true
            this.licenceImgUrls = []
            const { data } = await getDeclarePermitInfo(row.id);
			const entData = await getLicenceBaseInfo();
			const result = data.data;
			result.name = entData.data.entData.name
			result.chargePerson = entData.data.entData.chargePerson
			result.licenceImgUrls = [{
				name: '辐射安全许可证',
				url: result.licenceImgUrls
            }]
            this.licenceImgUrls = [result.licenceImgUrls[0].url]
			this.licenceInfo = result;
            this.dialogVisible = true
        },
        /**
         * @desc 申报数据提交
         */
        submitLicenceInfo() {
            if(!this.licenceInfo.enterpriseType){
                return this.$message({ message: '请选择单位类型！', type: 'warning' })
            } else if(!this.licenceInfo.enterpriseStatus) {
                return this.$message({ message: '请选择单位状态！', type: 'warning' })
            } else if(!this.licenceInfo.dateOfIssue) {
                return this.$message({ message: '选择发证日期', type: 'warning' })
            }else if(!this.licenceInfo.effectiveDate) {
                return this.$message({ message: '选择有效日期', type: 'warning' })
            }
            this.$confirm('确定要提交吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$refs.uploadFile.submit()
                if(!this.fileUpload){
                    this.$message({
                        message: '许可证图片必须上传！',
                        type: 'warning'
                    })
                }
                this.fileUpload?.then(
                    file => {
                        if(file.length) {
                            this.licenceInfo.licenceImgUrls = [file]
                            const senData = cloneDeep(this.licenceInfo);
                            senData.licenceImgUrls = file;
                            senData.effectiveDate = moment(senData.effectiveDate).format('YYYY-MM-DD')
                            senData.dateOfIssue = moment(senData.dateOfIssue).format('YYYY-MM-DD')
                            InsertDeclarePermit(senData).then(res => {
                                if(res.code === 200) {
                                    this.dialogVisible = false
                                    this.getList()
                                    return this.$message({
                                        type: "success",
                                        message: "申报成功"
                                    })
                                }
                                throw new Error('申报失败')
                            }).catch(e => {
                                this.dialogVisible = false
                            })
                        } else {
                            this.$message({
                                message: '许可证图片必须上传！',
                                type: 'warning'
                            })
                        }
                    }
                );
                // this.fileUpload = null;
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消提交'
                // });          
            });
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        // 上传文件提示
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        // 上传文件删除回调
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        // 关闭弹窗
        closeDialog() {
			this.isGO = false
            this.licenceInfo = {
                licenceImgUrls: []
            }
        },
        // 加载文件
        async htpRequest(params){
			console.log('arguments',arguments)
			this.fileUpload = this.loadFile(params.file)
		},
        // 加载文件
		loadFile(file){
			return new Promise((res, rej) => {
				const fileRead = new FileReader()
				fileRead.readAsDataURL(file)
				fileRead.onload = function(){
					res(this.result)
				}
				fileRead.onerror = function(){
					rej('读取失败')
				}
			})
		},
    },
}
